<?php
namespace app\common\model;
// 用户模型
use think\Model;
use app\common\model\TokenUser;

class User extends Model
{
	public $error = null; //如果存在错误的时候返回一下错误

    protected $readonly = ['username'];	// 只读字段

    protected $insert  = ['logins', 'reg_ip', 'last_time', 'last_ip'];	// 新增自动完成列表
//  protected $update = [];	//更新自动完成列表

    public function userInfo()
    {
        return $this->hasOne('userInfo', 'uid', 'id');
    }
    public function Focus()
    {
        return $this->hasOne('Focus', 'fuid', 'id');
    }

    public function userGroup()
    {
        return $this->hasMany('authGroupAccess', 'uid', 'id');
    }

    protected function setPasswordAttr($value)
    {
        return md5($value);
    }
    protected function setLoginsAttr()
    {
        return '0';
    }
    protected function setRegIpAttr()
    {
        return request()->ip();
    }
    protected function setLastTimeAttr()
    {
        return time();
    }
    protected function setLastIpAttr()
    {
        return request()->ip();
    }

    public function getStatusTurnAttr($value, $data)
    {
        $turnArr = [0=>lang('status0'), 1=>lang('status1')];
        return $turnArr[$data['status']];
    }
    public function getLastTimeTurnAttr($value, $data)
    {
        return date('Y-m-d H:i:s', $data['last_time']);
    }

	//用户登录
    public function login($username, $password) {
		if( empty($username) || empty($password) ){
			$this->error = '请填写用户名或密码';
			return false;
		}
		$user = User::get(['username'=>$username]);
		$user->userInfo;
		if( !empty($user) ){
            if($user['status'] != '1'){
                $this->error = '该账户已经禁用';
				return false;
            }elseif( $user['password'] != $password ){
                $this->error = '密码错误';
				return false;
            }else{
                // 更新登陆信息
                $ip = request()->ip();

                $updata = [
                    'logins' => $user['logins']+1,
                    'last_time' => time(),
                    'last_ip' => $ip,
                ];
                $where = ['id' => $user['id']];
                User::where($where)->update($updata);
                //设置session,cookie
                session('userId', $user['id']);
                $config = new \app\common\model\Config();
				$tkModel = new TokenUser();
                $login_time = $config->where(['type'=>'system', 'k'=>'login_time'])->value('v');
                $user_token = $tkModel->createToken($user['id'], 1, $login_time);
                session('user_token', $user_token);
                //登陆日志
                $ipStr = @file_get_contents("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=".$ip);   //.$ip
                if ($ipStr != '-2'){
                    $llModel = new \app\common\model\LoginLog();
                    $s = mb_strpos($ipStr, '{');
                    $e = mb_strpos($ipStr, '}');
                    $ipJsonStr = mb_substr($ipStr, $s, $e-$s+1);
                    $ipArr = json_decode($ipJsonStr, true);
                    $logData = [
                            'uid' => $user['id'],
                            'ip' => $ip,
                            'country' => $ipArr['country'],
                            'province' => $ipArr['province'],
                            'city' => $ipArr['city'],
                            'district' => $ipArr['district']
                    ];
                    $llModel->save($logData);
                }
                return true;
			}
		}else{
			$this->error = '用户不存在';
			return false;
		}
    }




}